package com.ycj.entropy;

import androidx.appcompat.app.AppCompatActivity;

import android.app.DownloadManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.ycj.entropy.data.DaoFactory;
import com.ycj.entropy.data.Study;
import com.ycj.entropy.data.StudyDao;
import com.ycj.entropy.util.CameraUtil;
import com.ycj.entropy.util.DateUtil;

import org.jetbrains.annotations.NotNull;

import java.io.Serializable;
import java.util.Date;

public class BrowseStudyActivity extends AppCompatActivity {

    private Study study;
    private ViewGroup imageContainer;
    private TextView txtTitle;
    private TextView txtContent;
    private TextView txtTimeAddress;
    private View btnDelete;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_browse_study);

        this.study = (Study) getIntent().getSerializableExtra("model");

        init();
    }

    private void init() {
        this.imageContainer = findViewById(R.id.browse_images);
        this.txtTitle = findViewById(R.id.browse_txt_title);
        this.txtContent = findViewById(R.id.browse_txt_content);
        this.txtTimeAddress = findViewById(R.id.browse_txt_time_address);
        this.btnDelete = findViewById(R.id.browse_btn_delete);

        this.txtTimeAddress.setText(formatTimeAddress());
        this.txtTitle.setText(this.study.getTitle());
        this.txtContent.setText(this.study.getContent());

        this.btnDelete.setOnClickListener(v->{
            DaoFactory.init(this);
            StudyDao studyDao = DaoFactory.studyDao();
            studyDao.delete(this.study);
            Toast.makeText(this, "删除成功", Toast.LENGTH_LONG).show();
            this.finish();
        });

        fillImage();
    }

    private void fillImage() {
        for (String imageName : this.study.imageList()) {
            Bitmap imageBitmap = CameraUtil.getImageThumbnail(CameraUtil.storageDir(this), imageName, 1024, 1024);
            ImageView imageView = new ImageView(this);
            imageView.setImageBitmap(imageBitmap);
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setPadding(0,5,0,5);
            this.imageContainer.addView(imageView);
        }
    }

    @NotNull
    private String formatTimeAddress() {
        return String.format("时间:%s   地点:%s", DateUtil.format(this.study.getCreateAt()), this.study.getAddress());
    }


}